package com.app114.app.android.rk;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.SearchManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Patterns;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.WebView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.app114.app.android.rk.utils.FileUtil;
import com.app114.app.android.rk.webkit.ExtendedWebChromeClient;
import com.app114.app.android.rk.webkit.ExtendedWebChromeClient.WebChromeClientListener;
import com.app114.app.android.rk.webkit.ExtendedWebViewClient;
import com.app114.app.android.rk.webkit.ExtendedWebViewClient.WebClientListener;
import com.app114.app.android.rk.webkit.WebviewUtils;
import com.app114.app.android.rk.widget.ExtendedWebView;

public class BrowserActivity extends BaseFragmentActivity implements WebClientListener, WebChromeClientListener, DownloadListener {
	private ExtendedWebView mWebView;
	// Google search
	private final static String QuickSearch_G = "http://www.google.com/m?q=%s";
	private final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
	private final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
	private final static String QUERY_PLACE_HOLDER = "%s";
	private final static String DEFAULT_HOME_PAGE = "http://douwaner.sinaapp.com/";

	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
		view.loadUrl(url);
		return true;
	}

	/**
	 * 过滤按键事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
			mWebView.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		// intent.setDataAndType(Uri.parse(url), mimetype);
		intent.setData(Uri.parse(url));
		startActivity(intent);
		// Intent intent = new Intent();
		// intent.setAction("android.intent.action.VIEW");
		// intent.setClassName("com.android.browser","com.android.browser.BrowserActivity");
		// intent.setDataAndType(Uri.parse(url), mimetype);
		// startActivity(intent);
	}

	@Override
	protected void activitySetup(Bundle savedInstanceState) {
		Intent intent = getIntent();
		if (intent == null) {
			return;
		}
		String action = intent.getAction();
		String url = "";
		if (action.equals(Intent.ACTION_VIEW)) {
			url = smartUrlFilter(intent.getData());
		} else if (Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
				|| Intent.ACTION_WEB_SEARCH.equals(action)) {
			url = intent.getStringExtra(SearchManager.QUERY);
			if (url != null) {
				// In general, we shouldn't modify URL from Intent.
				// But currently, we get the user-typed URL from search box as well.
				url = fixUrl(url);
				url = smartUrlFilter(url);
			}
		}

		setContentView(R.layout.layout_web);
		setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
		mWebView = (ExtendedWebView) findViewById(R.id.webview);
		mWebView.setDownloadListener(this);
		WebviewUtils.webViewSettings(mWebView);
		mWebView.setWebViewClient(new ExtendedWebViewClient(this));
		mWebView.setWebChromeClient(new ExtendedWebChromeClient(this));
		mWebView.requestFocus();
		if (url.equals("")) {
			url = DEFAULT_HOME_PAGE;
		}
		mWebView.loadUrl(url);
		fullScreen();
	}

	static String fixUrl(String inUrl) {
		// FIXME: Converting the url to lower case
		// duplicates functionality in smartUrlFilter().
		// However, changing all current callers of fixUrl to
		// call smartUrlFilter in addition may have unwanted
		// consequences, and is deferred for now.
		int colon = inUrl.indexOf(':');
		boolean allLower = true;
		for (int index = 0; index < colon; index++) {
			char ch = inUrl.charAt(index);
			if (!Character.isLetter(ch)) {
				break;
			}
			allLower &= Character.isLowerCase(ch);
			if (index == colon - 1 && !allLower) {
				inUrl = inUrl.substring(0, colon).toLowerCase() + inUrl.substring(colon);
			}
		}
		if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
			return inUrl;
		if (inUrl.startsWith("http:") || inUrl.startsWith("https:")) {
			if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
				inUrl = inUrl.replaceFirst("/", "//");
			} else
				inUrl = inUrl.replaceFirst(":", "://");
		}
		return inUrl;
	}

	private String smartUrlFilter(Uri inUri) {
		if (inUri != null) {
			return smartUrlFilter(inUri.toString());
		}
		return null;
	}

	private String smartUrlFilter(String url) {

		String inUrl = url.trim();
		boolean hasSpace = inUrl.indexOf(' ') != -1;

		Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
		if (matcher.matches()) {
			// force scheme to lowercase
			String scheme = matcher.group(1);
			String lcScheme = scheme.toLowerCase();
			if (!lcScheme.equals(scheme)) {
				inUrl = lcScheme + matcher.group(2);
			}
			if (hasSpace) {
				inUrl = inUrl.replace(" ", "%20");
			}
			return inUrl;
		}
		if (!hasSpace) {
			if (Patterns.WEB_URL.matcher(inUrl).matches()) {
				return URLUtil.guessUrl(inUrl);
			}
		}

		// FIXME: Is this the correct place to add to searches?
		// what if someone else calls this function?

		return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
	}

	protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile("(?i)" + // switch on case insensitive matching
			"(" + // begin group for schema
			"(?:http|https|file|rtsp):\\/\\/" + "|(?:inline|data|about|javascript):" + ")" + "(.*)");

	@Override
	protected boolean _onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.activity_browser, menu);
		return true;
	}

	@Override
	protected boolean _onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// case R.id.menu_refresh:
		// mWebView.reload();
		// break;
		case R.id.menu_fullScreen:
			getSupportActionBar().hide();
			break;
		case R.id.menu_share:
			Intent intent = new Intent(this, ShareDialog.class);
			try {
				intent.putExtra("data", shot());
				intent.putExtra("title",mWebView.getTitle());
				startActivity(intent);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;

		default:
			break;
		}
		return true;
	}

	/**
	 * 截屏方法
	 * 
	 * @return
	 * @throws IOException
	 */
	private String shot() throws IOException {
		View view = getWindow().getDecorView();
		Display display = this.getWindowManager().getDefaultDisplay();
		view.layout(0, 0, display.getWidth(), display.getHeight());
		view.setDrawingCacheEnabled(true);// 允许当前窗口保存缓存信息，这样getDrawingCache()方法才会返回一个Bitmap
		Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache());

		return FileUtil.savePic(mContext, bmp);
	}

	private String capture() throws IOException {
		Picture pic = mWebView.capturePicture();

		int width = pic.getWidth();

		int height = pic.getHeight();

		if (width > 0 && height > 0) {

			Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

			Canvas mCanvas = new Canvas(bmp);

			pic.draw(mCanvas);

			FileUtil.savePic(mContext, bmp);
		}
		return "";
	}

	@Override
	protected void activityDestory() {
		// TODO Auto-generated method stub

	}
}
